const { getUserId } = require('../../utils')

const article = {
  async article (parent, { id }, ctx, info) {
    return ctx.db.query.article({ where: { id } }, info)
  },
  async articles (parent, { userId, cooperationId, first, skip, after }, ctx, info) {
    const where = {}
    // 这里的 AND 条件出错, 应该是 OR 所有的 Share 条件
    if (!userId) {
      // 没有 userId, 表示查询自己的 article 列表
      userId = getUserId(ctx)
      where.OR = [
        {
          owner: {
            id: userId
          }
        },
        {
          cooperations_some: {
            user: {
              id: cooperationId
            }
          }
        }
      ]
    } else {
      // 查询 user 的 article 列表
      // share PUBLIC || WHITELIST 并且当前用户在 WHITELIST || SUBSCRIBER 并且当前用户在 SUBSCRIBER
      where.AND = [{
        OR: [{
          owner: {
            id: userId
          }
        },
        {
          cooperations_some: {
            user: {
              id: cooperationId
            }
          }
        }]
      }, {
        OR: [{
          share: 'PUBLIC'
        }]
      }]
    }
    return ctx.db.query.articles({
      first,
      skip,
      after,
      where
    }, info)
  },
  async articlesConnection (parent, { cooperationId, first, skip, after, last, before }, ctx, info) {
    const userId = getUserId(ctx)
    return ctx.db.query.articlesConnection({
      first,
      skip,
      after,
      last,
      before,
      where: {
        OR: [
          {
            owner: {
              id: userId
            }
          },
          {
            cooperations_some: {
              user: {
                id: cooperationId
              }
            }
          }
        ]
      }
    }, info)
  },
  async articleExists (parent, { id }, ctx, info) {
    const userId = getUserId(ctx)
    return ctx.db.exists.Article({
      AND: [{
        id
      }, {
        OR: [{
          owner: {
            id: userId
          }
        },
        {
          cooperations_some: {
            user: {
              id: userId
            }
          }
        }]
      }]
    }, info)
  },
  async articlesExists (parent, { articleIds }, ctx, info) {
    const userId = getUserId(ctx)
    return ctx.db.query.articlesConnection({
      where: {
        AND: [{
          id_in: articleIds
        }, {
          OR: [{
            owner: {
              id: userId
            }
          },
          {
            cooperations_some: {
              user: {
                id: userId
              }
            }
          }]
        }]
      }
    }, info)
  }
}

module.exports = { article }
